import { forEach } from "lodash";
import { apiData } from "./stores/apiData";
import { ref } from "vue";
import request from "./request";

export const runApiDataResult = ref({});
export const broadcastData = ref({});

// 执行接口
export async function runApi(opts) {
  const apidataDom = apiData();
  const apiDataList = apidataDom.getInfo;
  let apiResult = null;
  forEach(apiDataList, (item) => {
    if (item.url === opts.url) {
      apiResult = { ...item };
    }
  });
  if (apiResult?.type === "2") {
    runApiDataResult.value = {
      id: "当前组件的唯一标识",
      url: opts.url,
      result: JSON.parse(apiResult.staticData),
    };
  } else if (apiResult?.type === "1") {
    let funcString = `(data) => { 
  
  
      return data}`;
    let func = new Function(`return ${apiResult.inData || funcString}`)();
    let res = func({ data: opts?.data });
    if (res === -1 || res === "-1") {
      return;
    }
    if (apiResult.apiType === "2") {
      res = await request({
        url: apiResult.url,
        method: apiResult.method,
        params: res,
        data: res,
      });
    }
    func = new Function(`return ${apiResult.outData || funcString}`)();
    let result = func(res);
    runApiDataResult.value = {
      id: "当前组件的唯一标识",
      url: opts.url,
      result: result,
    };
  }
}
export async function runFetch(opts) {
  const apidataDom = apiData();
  const apiDataList = apidataDom.getInfo;
  let apiResult = null;
  forEach(apiDataList, (item) => {
    if (item.url === opts.url) {
      apiResult = { ...item };
    }
  });
  if (apiResult?.type === "2") {
    runApiDataResult.value = {
      id: "当前组件的唯一标识",
      url: opts.url,
      result: JSON.parse(apiResult.staticData),
    };
  } else if (apiResult?.type === "1") {
    let funcString = `(data) => { 
  
  
      return data}`;
    let func = new Function(`return ${apiResult.inData || funcString}`)();
    let res = func({ data: opts?.data });
    if (res === -1 || res === "-1") {
      return;
    }
    if (apiResult.apiType === "2") {
      res = await fetchApi(apiResult.url, apiResult.method, res);
    }
    func =  new Function(`return ${apiResult.inData || funcString}`)();
    let result = func(res);
    runApiDataResult.value = {
      id: "当前组件的唯一标识",
      url: opts.url,
      result: result,
    };
  }
}

export async function fetchApi(url, method, options = {}) {
  // 默认配置
  const defaultOptions = {
    method: method,
    headers: {
      "Content-Type": "application/json",
    },
    ...options, // 用户传入的 options 会覆盖默认配置
  };

  // 如果是POST请求并且有 body，处理为 JSON 字符串
  if (defaultOptions.method === "POST" && defaultOptions.body) {
    defaultOptions.body = JSON.stringify(defaultOptions.body);
  }

  try {
    const response = await fetch(url, defaultOptions);

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 返回 JSON 格式的数据
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Fetch error:", error);
    throw error; // 重新抛出错误，以便调用时处理
  }
}

export async function runPublicFun(opts) {
  // key时间名 ownStore 自由数据
  let data = await import("@/part/publicFun.json");
  return data[opts.key];
}

export function broadcast(data) {
  broadcastData.value = data;
}
